﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json.Linq;


//http://getpocket.com/developer/docs/authentication
//http://james.newtonking.com/pages/json-net.aspx


namespace JbolanoPocketSync
{
    class Program
    {
        static void Main(string[] args)
        {
#if DEBUG
            args = new string[1];
            args[0] = @"C:\Users\JoseAngel\Downloads\pocket";
#endif
            oAuth auth;
            DirectoryInfo dir;

            try
            {
                dir = new DirectoryInfo(args[0]);
                if (!dir.Exists)
                {
                    throw new Exception("Invalid path.");
                }
            }catch{
                Console.WriteLine(@"This tools needs a valid local path in order to save webpages to disk.");
                Console.WriteLine(@"You must specify a valid path in the form: C:\>JbolanoPocketSync.exe c:\temp");
                return;
            }

            auth = Authenticate(dir);

            //Get stuff done...
            Articles articles = new Articles(auth.code, auth.access_token, dir.FullName);
            
            articles.GetRemoteList();
            articles.PrepareSync(dir);
            articles.UpdatePocket();
            
            RemoveReadedLocalItems(articles, dir);            
            articles.DownloadNewContent();

            Console.WriteLine("Process completed.");

#if DEBUG
                Console.WriteLine("Press any key to end...");
                Console.ReadKey();                
#endif

        }

        public static void RemoveReadedLocalItems(Articles articles, DirectoryInfo dir)
        {
            Console.WriteLine("Deleting {0} readed items from local folder.", articles.listToArchive.Count);
            foreach (Article a in articles.listToArchive)
            {
                Directory.Delete(dir.FullName + @"\" + a.item_id, true);
            }
            
            List<string> filesToDelete = new List<string>();
            List<string> dirsToDelete = new List<string>();

            foreach (FileInfo f in dir.GetFiles("*.html"))
            {
                bool toDelete = true;
                foreach (Article a in articles.listOnRemote)
                {
                    if (articles.RemoveBadChars(a.given_title) + ".html" == f.Name)
                    {
                        toDelete = false;
                    }
                }

                if (toDelete)
                {
                    filesToDelete.Add(f.FullName);
                }
            }

            foreach (DirectoryInfo f in dir.GetDirectories())
            {
                bool toDelete = true;
                foreach (Article a in articles.listOnRemote)
                {
                    if (a.item_id == f.Name)
                    {
                        toDelete = false;
                    }
                }

                if (toDelete)
                {
                    dirsToDelete.Add(f.FullName);
                }
            }

            foreach (string path in filesToDelete)
            {
                File.Delete(path);
            }
            foreach (string path in dirsToDelete)
            {
                Directory.Delete(path, true);
            }
        }

        public static oAuth Authenticate(DirectoryInfo dir)
        {
            FileInfo conf = new FileInfo(dir.FullName + @"\auth.conf");
            oAuth auth;
            if (conf.Exists)
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(conf.FullName)){
                    auth = JsonConvert.DeserializeObject<oAuth>(sr.ReadToEnd());
                }
            }
            else
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(conf.FullName, false)){
                    auth = new oAuth(true);
                    sw.WriteLine(JsonConvert.SerializeObject(auth));
                }
            }
            return auth;
        }
    }
    
}
